#include <stdio.h>
#include "pico8_font5x6.xpm"

const int font_width  = 8;
const int font_height = 11;
const int char_per_line = 16;
const int lines = 4;

char digit_to_hex(int x) {
   if(x < 10) {
      return ('0' + x);
   } else {
      return ('a' + (x - 10));
   }
}

char digit_to_HEX(int x) {
   if(x < 10) {
      return ('0' + x);
   } else {
      return ('A' + (x - 10));
   }
}

char* int_to_hex(int x) {
   static char buf[3] = {0,0,0};
   buf[0] = digit_to_hex(x >> 4);
   buf[1] = digit_to_hex(x & 15);
   return buf;
}

void printb(int x) {
   for(int b=0; b<8; ++b) {
      printf("%c", (x & (1<<b)) ? '*' : ' ');
   }
}


int get_font_column(int c, int column) {
   int result = 0;
   int char_line   = c / char_per_line;
   int char_column = c % char_per_line;
   for(int i=2; i<10; ++i) {
      int xpm_line   = 4 + (char_line * font_height) + i;
      int xpm_column = (char_column * font_width) + column;
      if(pico8_font5x6_xpm[xpm_line][xpm_column] != ' ') {
	  result = result | (1 << (i-2));
      }
   }
/* 
   printb(result);
   printf("\n"); */
   return result;
}


unsigned int font_data[255];

void print_char(char c) {
    unsigned int chardata = font_data[c - ' '];
    int shifted = chardata & (1 << 30);
    printf("--------------------\n");   
    for(int row=0; row<8; ++row) {
	for(int col=0; col<5; ++col) {
	    unsigned int coldata = (chardata >> (6 * col)) & 63 ;
	    if(shifted) {
		coldata = coldata << 2;
	    }
	    unsigned int BW = coldata & (1 << row);
	    printf("%c",BW?'*':' ');
	}
	printf("\n");
    }
    printf("--------------------\n");
}

int main() {

    printf("# Generated by FIRMWARE/TOOLS/FONT/makefont.c\n");
    printf(".globl font_5x6\n");
    printf(".LC0:\n");
    for(int car=0; car < 16*6; ++car) {
      unsigned int col1 = get_font_column(car, 2);
      unsigned int col2 = get_font_column(car, 3);
      unsigned int col3 = get_font_column(car, 4);
      unsigned int col4 = get_font_column(car, 5);
      unsigned int col5 = get_font_column(car, 6);	 

      int shifted = 0;
       
      // p,q,g ... shifted by two pixels.  
      if(col1 > 63 || col2 > 63 || col3 > 63 || col4 > 63 || col5 > 63) {
	 shifted = 1;
	 col1 = col1 >> 2;
	 col2 = col2 >> 2;
	 col3 = col3 >> 2;
	 col4 = col4 >> 2;
	 col5 = col5 >> 2;	 
      }
      unsigned int charcode = 
	 col1           |
	(col2    << 6 ) |
	(col3    << 12) |
	(col4    << 18) |
	(col5    << 24) |
	(shifted << 30) ;
      printf(".word 0x%08lx\n", charcode);
      font_data[car] = charcode;
//    printf("\n");
   }
    printf("font_5x6:\n");
    printf("    .word .LC0\n");	
      


   
//   print_char(' ');
//   print_char('P');
//   print_char('p');   

}
